try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET
from urlparse import urljoin

"""
TODO need to go through and make sure that the combination of variables and scope works properly.
Need to make sure that combining each of the features so variables and scopes works properly.
"""

class RESTAPILayout:

    def __init__(self, xml):
        structure = ET.parse(xml)
        self.root = structure.getroot()

    def parse(self, query):
        query = query.strip()
        items = query.split(" ")
        return self.parseTree(items, [], self.root)

    def parseTree(self, items, variables, root):
        for tag in root.iter():
            if tag.attrib.get('name') == items[0]:
                if tag.tag == "variable":
                    if len(items) == 2:
                        query = self.addVariables(tag.attrib.get('ext'), variables)
                        return urljoin(query, items[1])
                    else:
                         variables.append(items[1])
                         return self.parseTree(items[2:], variables, tag)
                elif tag.tag == "scope":
                    if len(items) == 1:
                        query = self.addVariables(tag.attrib.get('ext'), variables)
                        return query
                    else:
                        return self.parseTree(items[1:], variables, tag)
                    
    def addVariables(self, query, variables):
        for variable in variables:
            query = query.split("{", 1)
            query = query[0] + variable + query[1].split("}",1)[1]
            #query = urljoin(urljoin(query[0], variable), query[1].split("}", 1)[1])
        return query

    def getRoot(self):
        return self.root


